/**
 * Created by jt on 2017/5/7.
 */
import "./index.less";
import "../../../unit/common/js/bootstrap_js/select2.min.js";
import "../../../unit/common/js/bootstrap_js/jquery.dataTables.js";
import "../../../unit/common/js/bootstrap_js/form-samples.js";
import "../../../unit/common/js/bootstrap_js/bootstrap-datetimepicker.js";
import "../../../unit/common/js/bootstrap_js/bootstrap-datetimepicker.zh-CN.js";
import "../../../unit/common/js/bootstrap_js/table-editable.js";

import {projSts} from "../config.js";
import projListTpl from "./getProj.handlebars";
import paginationTpl from "./paging.handlebars";

var token = sessionStorage.getItem('token');
if (token == null || token =='') {
    location.href = HOST_FRT+'/logins/login.html';
}

var orgList = sessionStorage.getItem("manageCompanies");
var orgId = sessionStorage.getItem("orgId");
var orgJsonObj = JSON.parse(orgList);
if(orgJsonObj.length){
    for(var i=0; i<orgJsonObj.length; i++){
        if(orgJsonObj[i].parent_dept_id==1){
            var selected="";
            if(orgJsonObj[i].id==orgId){
                selected = "selected";
            }
            jQuery('.searOrgId').append('<option value="'+orgJsonObj[i].id+'" ' + selected + '>'+orgJsonObj[i].dept_name+'</option>');
        }
    }
}else{
    alert("该采购员无所辖公司");
}
var selectedOrgId = jQuery('.searOrgId').val();
var beginTim = new Date(new Date().setMonth(new Date().getMonth()-1)).Format("yyyy-MM-dd 00:00");
var endTim = new Date().Format("yyyy-MM-dd hh:mm");
jQuery('.searTimBgnStr').val(beginTim);
jQuery('.searTimEndStr').val('');
jQuery('.datetimepicker').datetimepicker({
    language: 'zh-CN',
    weekStart: 1,
    todayBtn: 1,
    autoclose: 1,
    todayHighlight: 1,
    startView: 2,
    minView: 0, //0表示分钟（默认），1表示小时，而2表示天
    forceParse: 0,
    showMeridian: 1,
    format: 'yyyy-mm-dd hh:ii'///
});

var projList = {
    pageNo: 1,
    pageSize: 20,
    maxPage: 1,
    isFirstPage: false,
    isLastPage: false,
    total: 0,
    data:{
        "crtTimBgnStr":beginTim+':00',    // 开始时间
        "orgId":selectedOrgId
    },
    init: function(){
        this.getProjData()
            .then(this.renderprojList)
            .then(this.renderPagination)
            .then(this.bindEvent);
    },
    getProjData: function() {
        return new Promise((resolve, reject)=>{
            let self = this;
            $.ajax({
                url: HOST_ADDR + `/cpmp/bidProjOff/queryByConds/${self.pageNo}/${self.pageSize}`,
                type: 'post',
                dataType: 'json',
                headers: {
                    'access_token': token,'login_type':'ums'
                },
                data:JSON.stringify(self.data),
                contentType: "application/json",
                success: function (resp) {
                    if (resp.success) {
                        console.log(resp);
                        resolve(resp);
                    }
                    else {
                        alert(resp.msgInf);
                    }
                },
                error: function (err) {
                    console.log(err);
                }
            });

        });

    },
    // 渲染列表
    renderprojList: function(resp){
        let self = projList;
        // 处理数据begin
        self.total = resp.data.count;
        self.isFirstPage = self.pageNo === 1;
        self.maxPage = Math.ceil(self.total / self.pageSize);
        $.each(resp.data.list,function(index,item){
            item.projNbrFmt = item.projNbr || '';
            item.projAvailabel = (item.projSts != '-10');
            item.redAvailabel = (item.projSts == '-20');
            item.projStsFmt = projSts[item.projSts] || '暂无状态';
            item.viewsetAvailabel = (item.projSts == '40' || item.projSts == '50');
        });

        // 处理数据end
        if(self.pageNo * self.pageSize >= self.total){
            self.isLastPage = true;
        }else{
            self.isLastPage = false;
        }

        let resultHtml = projListTpl({projList: resp.data.list});
        $('#sample_editable_1 tbody').html(resultHtml);
    },

    // 渲染分页
    renderPagination: function(){
        let self = projList;
        let pageList = [];
        for(let i=0; i<self.maxPage; i++){
            pageList.push({idx: i+1});
        }
        console.log(self.total);
        let paginationHtml = paginationTpl({
            begin: (self.pageNo-1) * self.pageSize + 1,
            end: self.isLastPage ? self.total : self.pageNo * self.pageSize,
            total: self.total,
            isLastPage: self.isLastPage,
            isFirstPage: self.isFirstPage,
            pageList: pageList

        });
        $('.J_pagination').html(paginationHtml);
        $('.page-item').each((index,item)=>{
            if($(item).data('index')===self.pageNo){
                console.log(this);
                $(item).addClass('active');
            }
            //最多显示7个页码
            if (Math.abs($(item).data('index')-self.pageNo) > 3) {
                $(item).css('display','none');
            }

        });
    },

    // 绑定事件
    bindEvent: function(){
        let self = projList;
        $('.J_prev').unbind().click(function(){
            if(self.pageNo > 1){
                self.pageNo = self.pageNo -1;
                self.renderList();
            }
        });
        $('.J_next').unbind().click(function(){
            if(self.pageNo < self.maxPage){
                self.pageNo = self.pageNo + 1;
                self.renderList();
            }

        });
        //首尾页
        $('.isFirst').unbind().click(function(){
            if(self.pageNo != 1){
                self.pageNo = 1;
                self.renderList();
            }
        });
        $('.isLast').unbind().click(function(){
            if(self.pageNo != self.maxPage){
                self.pageNo = self.maxPage;
                self.renderList();
            }
        });
        $('.page-item').unbind().click(function(){
            let $item = $(this);

            if(!$item.hasClass('active')){
                self.pageNo = $item.data('index');
                self.renderList();
            }
        });

        //搜索
        jQuery('.searchPro').unbind().click(function(){
            var searNam = jQuery('.searNam').val();
            var searStatus = jQuery('.searStatus').val();
            var orgId = jQuery('.searOrgId').val();
            var searTimBgnStr = jQuery('.searTimBgnStr').val();
            var searTimEndStr = jQuery('.searTimEndStr').val();
            self.data={};
            if (searNam != '' && searNam != null) {
                self.data.projNam = searNam;
            }
            if (searStatus != '' && searStatus != null) {
                self.data.projSts = searStatus;
            }
            if (orgId != '' && orgId != null) {
                self.data.orgId = orgId;
            }
            if (searTimBgnStr != '' && searTimBgnStr != null) {
                self.data.crtTimBgnStr = searTimBgnStr+":00";
            }
            if (searTimEndStr != '' && searTimEndStr != null) {
                self.data.crtTimEndStr = searTimEndStr+":00";
            }
            self.renderList();
        });

    },

    // 渲染列表
    renderList(){
        this.getProjData()
            .then(this.renderprojList)
            .then(this.renderPagination)
            .then(this.bindEvent);
    }
};

App.init();
projList.init();

jQuery('.logOut').attr('href','../logins/login.html');